package com.yuanqi.contoller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqi.entity.Inventory;
import com.yuanqi.entity.InventoryTxn;
import com.yuanqi.entity.Product;
import com.yuanqi.entity.Sku;
import com.yuanqi.entity.WareWarehouse;
import com.yuanqi.mapper.InventoryMapper;
import com.yuanqi.mapper.InventoryTxnMapper;
import com.yuanqi.mapper.ProductMapper;
import com.yuanqi.mapper.SkuMapper;
import com.yuanqi.mapper.WareWarehouseMapper;
import com.yuanqi.service.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 库存管理控制器
 */
@RestController
@RequestMapping("/inventory")
public class InventoryController {

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    private InventoryTxnMapper inventoryTxnMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private WareWarehouseMapper warehouseMapper;

    /**
     * 库存状况分页列表（含关联字段）
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) Long skuId,
            @RequestParam(required = false) Integer stockStatus,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String sortOrder,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) String specification,
            @RequestParam(required = false) String warehouseName
    ) {
        Page<Inventory> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Inventory> qw = new LambdaQueryWrapper<>();

        if (warehouseId != null) {
            qw.eq(Inventory::getWarehouseId, warehouseId);
        }
        if (skuId != null) {
            qw.eq(Inventory::getSkuId, skuId);
        }

        // 模糊筛选（仓库名、商品名、规格编号）
        try {
            if (StringUtils.hasText(warehouseName)) {
                List<WareWarehouse> ws = warehouseMapper.selectList(
                        new LambdaQueryWrapper<WareWarehouse>().like(WareWarehouse::getWhName, warehouseName)
                );
                if (ws != null && !ws.isEmpty()) {
                    List<Long> wids = new ArrayList<>();
                    for (WareWarehouse w : ws) { wids.add(w.getId()); }
                    qw.in(Inventory::getWarehouseId, wids);
                } else {
                    Map<String, Object> empty = new HashMap<>();
                    empty.put("records", Collections.emptyList());
                    empty.put("total", 0);
                    empty.put("pages", 0);
                    empty.put("current", page);
                    empty.put("size", size);
                    return ResponseEntity.ok(empty);
                }
            }

            List<Long> skuIdsFilter = new ArrayList<>();
            if (StringUtils.hasText(productName)) {
                List<Product> products = productMapper.selectList(
                        new LambdaQueryWrapper<Product>().like(Product::getProductName, productName)
                );
                if (products != null && !products.isEmpty()) {
                    List<Long> pids = new ArrayList<>();
                    for (Product p : products) { pids.add(p.getId()); }
                    List<Sku> skus = skuMapper.selectList(
                            new LambdaQueryWrapper<Sku>().in(Sku::getProductId, pids)
                    );
                    for (Sku s : skus) { skuIdsFilter.add(s.getId()); }
                }
            }
            if (StringUtils.hasText(specification)) {
                List<Sku> skusByCode = skuMapper.selectList(
                        new LambdaQueryWrapper<Sku>().like(Sku::getSkuCode, specification)
                );
                for (Sku s : skusByCode) { skuIdsFilter.add(s.getId()); }
            }
            if (!skuIdsFilter.isEmpty()) {
                qw.in(Inventory::getSkuId, skuIdsFilter);
            }
        } catch (Exception ignore) {
        }

        // 库存状态过滤（示例：>10 正常，0<且<=10 预警，=0 缺货）
        if (stockStatus != null) {
            switch (stockStatus) {
                case 1: // 正常
                    qw.gt(Inventory::getOnHandQty, new java.math.BigDecimal(10));
                    break;
                case 2: // 预警
                    qw.gt(Inventory::getOnHandQty, java.math.BigDecimal.ZERO)
                      .le(Inventory::getOnHandQty, new java.math.BigDecimal(10));
                    break;
                case 3: // 缺货
                    qw.eq(Inventory::getOnHandQty, java.math.BigDecimal.ZERO);
                    break;
                default:
            }
        }

        // 排序
        if (StringUtils.hasText(sortBy)) {
            boolean isAsc = "ascending".equalsIgnoreCase(sortOrder);
            switch (sortBy) {
                case "id":
                    qw.orderBy(true, isAsc, Inventory::getId);
                    break;
                case "quantity":
                    qw.orderBy(true, isAsc, Inventory::getOnHandQty);
                    break;
                case "updatedAt":
                    qw.orderBy(true, isAsc, Inventory::getUpdatedAt);
                    break;
                default:
                    qw.orderByDesc(Inventory::getUpdatedAt);
            }
        } else {
            qw.orderByDesc(Inventory::getUpdatedAt);
        }

        IPage<Inventory> pageResult = inventoryService.page(pageParam, qw);

        // 丰富返回字段
        List<Map<String, Object>> records = new ArrayList<>();
        for (Inventory inv : pageResult.getRecords()) {
            Map<String, Object> row = new HashMap<>();
            row.put("id", inv.getId());
            row.put("skuId", inv.getSkuId());
            row.put("warehouseId", inv.getWarehouseId());
            row.put("batchNo", inv.getBatchNo());
            row.put("expiryDate", inv.getExpiryDate());
            row.put("onHandQty", inv.getOnHandQty());
            row.put("availableQty", inv.getAvailableQty());
            row.put("updatedAt", inv.getUpdatedAt());
            // 对齐前端展示字段
            row.put("quantity", inv.getOnHandQty());

            try {
                Sku sku = skuMapper.selectById(inv.getSkuId());
                if (sku != null) {
                    row.put("skuCode", sku.getSkuCode());
                    row.put("specification", sku.getSkuCode());
                    Product product = productMapper.selectById(sku.getProductId());
                    if (product != null) {
                        row.put("productName", product.getProductName());
                        row.put("productCode", product.getSpuCode());
                    } else {
                        row.put("productName", "未知商品");
                        row.put("productCode", "未知");
                    }
                } else {
                    row.put("specification", "未知");
                    row.put("productName", "未知商品");
                    row.put("productCode", "未知");
                }

                WareWarehouse wh = warehouseMapper.selectById(inv.getWarehouseId());
                if (wh != null) {
                    // 仓库名称（两种键名都返回，方便前端对接）
                    row.put("whName", wh.getWhName());
                    row.put("warehouseName", wh.getWhName());

                    // 仓库类型（兼容不同实体/字段命名）
                    Object type = null;
                    try { type = wh.getClass().getMethod("getWarehouseType").invoke(wh); } catch (Exception ignore2) {}
                    if (type == null) {
                        try { type = wh.getClass().getMethod("getWhType").invoke(wh); } catch (Exception ignore3) {}
                    }
                    if (type != null) {
                        row.put("warehouseType", String.valueOf(type));
                    }
                }
            } catch (Exception ignore) {
            }

            records.add(row);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", pageResult.getTotal());
        result.put("pages", pageResult.getPages());
        result.put("current", pageResult.getCurrent());
        result.put("size", pageResult.getSize());
        return ResponseEntity.ok(result);
    }

    /**
     * 库存详情（单条，含关联字段）
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> detail(@PathVariable Long id) {
        Inventory inv = inventoryService.getById(id);
        if (inv == null) {
            return ResponseEntity.ok(Collections.emptyMap());
        }
        Map<String, Object> row = new HashMap<>();
        row.put("id", inv.getId());
        row.put("skuId", inv.getSkuId());
        row.put("warehouseId", inv.getWarehouseId());
        row.put("batchNo", inv.getBatchNo());
        row.put("expiryDate", inv.getExpiryDate());
        row.put("quantity", inv.getOnHandQty());
        row.put("onHandQty", inv.getOnHandQty());
        row.put("availableQty", inv.getAvailableQty());
        row.put("updatedAt", inv.getUpdatedAt());

        try {
            Sku sku = skuMapper.selectById(inv.getSkuId());
            if (sku != null) {
                row.put("skuCode", sku.getSkuCode());
                row.put("specification", sku.getSkuCode());
                Product product = productMapper.selectById(sku.getProductId());
                if (product != null) {
                    row.put("productName", product.getProductName());
                    row.put("productCode", product.getSpuCode());
                }
            }
            WareWarehouse wh = warehouseMapper.selectById(inv.getWarehouseId());
            if (wh != null) {
                row.put("whName", wh.getWhName());
            }
        } catch (Exception ignore) {
        }
        return ResponseEntity.ok(row);
    }

    /**
     * 入库记录（根据库存记录定位 SKU与仓库，再取正向流水）
     */
    @GetMapping("/{inventoryId}/in-records")
    public ResponseEntity<List<Map<String, Object>>> inRecords(@PathVariable Long inventoryId) {
        Inventory inv = inventoryService.getById(inventoryId);
        if (inv == null) {
            return ResponseEntity.ok(Collections.emptyList());
        }
        List<InventoryTxn> txns = inventoryTxnMapper.selectList(
                new LambdaQueryWrapper<InventoryTxn>()
                        .eq(InventoryTxn::getWarehouseId, inv.getWarehouseId())
                        .eq(InventoryTxn::getSkuId, inv.getSkuId())
                        .orderByDesc(InventoryTxn::getCreatedAt)
        );
        List<Map<String, Object>> rows = new ArrayList<>();
        for (InventoryTxn t : txns) {
            if ((t.getQty() != null && t.getQty().signum() > 0) ||
                    (t.getTxnType() != null && t.getTxnType().toUpperCase().contains("IN"))) {
                Map<String, Object> r = new HashMap<>();
                r.put("operateTime", t.getCreatedAt());
                r.put("quantity", t.getQty());
                r.put("reason", t.getTxnType());
                r.put("operator", "系统");
                r.put("remark", t.getRemark());
                rows.add(r);
            }
        }
        return ResponseEntity.ok(rows);
    }

    /**
     * 出库记录（根据库存记录定位 SKU与仓库，再取负向流水）
     */
    @GetMapping("/{inventoryId}/out-records")
    public ResponseEntity<List<Map<String, Object>>> outRecords(@PathVariable Long inventoryId) {
        Inventory inv = inventoryService.getById(inventoryId);
        if (inv == null) {
            return ResponseEntity.ok(Collections.emptyList());
        }
        List<InventoryTxn> txns = inventoryTxnMapper.selectList(
                new LambdaQueryWrapper<InventoryTxn>()
                        .eq(InventoryTxn::getWarehouseId, inv.getWarehouseId())
                        .eq(InventoryTxn::getSkuId, inv.getSkuId())
                        .orderByDesc(InventoryTxn::getCreatedAt)
        );
        List<Map<String, Object>> rows = new ArrayList<>();
        for (InventoryTxn t : txns) {
            if ((t.getQty() != null && t.getQty().signum() < 0) ||
                    (t.getTxnType() != null && t.getTxnType().toUpperCase().contains("OUT"))) {
                Map<String, Object> r = new HashMap<>();
                r.put("operateTime", t.getCreatedAt());
                r.put("quantity", t.getQty() == null ? null : t.getQty().abs());
                r.put("reason", t.getTxnType());
                r.put("operator", "系统");
                r.put("remark", t.getRemark());
                rows.add(r);
            }
        }
        return ResponseEntity.ok(rows);
    }



}